import React, { Component } from 'react'
import { add } from '../../store/actions/persion'
import { connect } from "react-redux";

class PersionUI extends Component {
  state = {
    name: '',
    age: 0,
    like: ''
  }
  componentDidMount() {
    // 回车添加事件
    document.onkeyup = (event) => {
      const theEvent = event || window.event || arguments.callee.caller.arguments[0];
      const code = theEvent.keyCode || theEvent.which || theEvent.charCode;
      if (code === 13) {
        this.addPersion()
      }
    }
  }
  // 保存表单数据
  saveFormData = (type) => {
    return (e) => {
      console.log('e.target.value', e.target.value)
      this.setState({
        [type]: e.target.value
      })
    }
  }
  addPersion = () => {
    const { name, age, like } = this.state
    console.log('拿到值', name, age, like)
    if (!name) {
      return alert('请输入姓名')
    }
    this.props.add({
      name,
      age,
      like,
      id: new Date().getTime()
    })
  }
  render() {
    const { count, persion } = this.props
    return (
      <div>
        <h2>我是Persion组件</h2>
        <div>拿到store中的count：{count}</div>

        <h5>员工列表：</h5>
        <div className="form-wrap">
          <label htmlFor="">
            昵称：
            <input type="text" ref={c => this.name = c} onChange={this.saveFormData('name')} />
          </label>
          <label htmlFor="">
            年龄：
            <input type="text" ref={c => this.age = c} onChange={this.saveFormData('age')} />
          </label>
          <label htmlFor="">
            爱好：
            <input type="text" ref={c => this.like = c} onChange={this.saveFormData('like')} />
          </label>
          <button onClick={this.addPersion}>新增</button>
        </div>

        <ul className="persion-list">
          {
            persion.map(item => {
              return (
                <li key={item.id}>
                  <span>{item.name}-</span>
                  <span>{item.age}-</span>
                  <span>{item.like}</span>
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}
export default connect(
  (store) => ({
    count: store.count,
    persion: store.persion
  }),
  {
    add
  }
)(PersionUI)